const { Service } = require("egg");

class BlogService extends Service {
    /**
     * 添加博客
     * @param {object} param0 博客信息
     */
    async create({ title, content, uid }) {
        // 解构参数
        let sql = "insert into blog (title, content, uid) values (?, ?, ?)";
        let params = [title, content, uid];
        let res = await this.app.mysql.query(sql, params);
        return res;
    }

    /**
     * 博客列表
     */
    async readList() {
        let sql = `
            select b.id as bid, b.title, b.content, b.create_time, b.uid, u.nickname
            from blog as b
            join user as u on b.uid = u.id
        `;
        let res = await this.app.mysql.query(sql);
        return res;
    }

    /**
     * 博客详情
     * @param {number} id 博客id
     */
    async find(id) {
        let sql = `
            select b.id as bid, b.title, b.content, b.create_time, b.uid, u.username, u.nickname
            from blog as b
            join user as u on b.uid = u.id
            where b.id = ?
        `;
        let params = [id];
        let res = await this.app.mysql.query(sql, params);
        return res[0];
    }

    /**
     * 修改博客信息
     * @param {object} blog 博客信息
     */
    async update({ id, title, content }) {
        let sql = "update blog set title = ?, content = ? where id = ?";
        let params = [title, content, id];
        let res = await this.app.mysql.query(sql, params);
        return res;
    }

    /**
     * 删除博客
     * @param {number} bid 博客id
     */
    async remove(bid) {
        let sql = "delete from blog where id = ?";
        let params = [bid];
        let res = await this.app.mysql.query(sql, params);
        return res;
    }
}

module.exports = BlogService;
